package com.yupi.usercenter.controller;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.usercenter.common.BaseResponse;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.common.Result;
import com.yupi.usercenter.common.ResultUtils;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.model.DTO.AuditFriendDTO;
import com.yupi.usercenter.model.DTO.MakeFriendDTO;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.model.request.UserLoginRequest;
import com.yupi.usercenter.model.request.UserRegisterRequest;
import com.yupi.usercenter.service.UserService;
import com.yupi.usercenter.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.yupi.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.yupi.usercenter.contant.UserConstant.USER_LOGIN_STATE;
@Slf4j
/**
 * 用户接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:3000",allowCredentials ="true")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private AliyunOSSOperator ossOperator;

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 校验
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            return null;
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前用户
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(loginUser);
    }


    /**
     * 删除用户
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 搜索用户
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<Page<User>> searchUsersByTags(@RequestParam(required = false) String keyWord,long pageNum, long pageSize) {
        Page<User> userList = userService.searchUser(keyWord, pageNum, pageSize);
        return ResultUtils.success(userList);
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {

        //  参数校验
        if (user == null || user.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User updateUser = new User();
        BeanUtils.copyProperties(user, updateUser);
        boolean result = userService.updateById(updateUser);
        log.info("修改用户信息成功");
        log.info("有修改：清除redis : {}", updateUser.getId());
        try {
            // 清除用户相关的Redis缓存
            redisTemplate.delete(String.format("yupao:user:login:%d", updateUser.getId()));
            redisTemplate.delete(String.format("yupao:user:id:%d", updateUser.getId()));
            redisTemplate.delete(String.format("yupao:user:recommend:%d", updateUser.getId()));
            log.info("用户 {} 信息更新，Redis缓存已清除", updateUser.getId());
        } catch (Exception e) {
            log.error("Redis缓存清除失败", e);
        }
        return ResultUtils.success(result ? 1 : 0);

    }

    /**
     * 分页查询用户列表
     */

    @GetMapping("/recommend")
   public BaseResponse<Page<User>> recommendUsers(long pageNum, long pageSize, HttpServletRequest request){
        //直接查询数据库
         //创一个MybatisPlus的分页对象
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(); //创建一个查询条件对象
        Page<User> page1 = userService.page(page, queryWrapper);
        return ResultUtils.success(page1);
    }

    /**
     * 获取最匹配的用户
     *
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.matchUsers(num, user));
    }

    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) throws Exception {
        log.info("上传文件：{}", file.getOriginalFilename());
        String url = ossOperator.upload(file.getBytes(), file.getOriginalFilename());
        return Result.success(url);

    }

    @GetMapping("/getUserDetatil")
    public BaseResponse<User> getUserDetatil(Long id) {
        User user = userService.getById(id);
        return ResultUtils.success(user);
    }

    @PostMapping("/makeFriend")
    public BaseResponse<String> makeFriend(@RequestBody MakeFriendDTO makeFriendDTO, HttpServletRequest request) {
        String result =  userService.makeFriend(makeFriendDTO, request);
        return ResultUtils.success(result);
    }

    @PostMapping("auditFriend")
    public BaseResponse<String> auditFriend(@RequestBody AuditFriendDTO auditFriendDTOt,HttpServletRequest request) {
        String result =  userService.auditFriend(auditFriendDTOt,request);
        return ResultUtils.success(result);
    }

    @GetMapping("/myFriend")
    public BaseResponse<List<User>> myFriend(String relationStatus ,HttpServletRequest request) {
        List<User> result =  userService.myFriend(relationStatus,request);
        return ResultUtils.success(result);
    }

    @GetMapping("/getUserById")
    public BaseResponse<User> getUserById(Long id) {
        User user = userService.getById(id);
        return ResultUtils.success(user);
    }



    private boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        User user = userService.getLoginUser(request);
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }

}
/**
 * 是否为管理员
 *
 * @param request
 * @return
 */